using DesktopWidgetApp.Shared;
using DesktopWidgetApp.UI.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DesktopWidgetApp.Core.Data
{
    /// <summary>
    /// 数据同步管理器
    /// 负责本地数据与服务器数据之间的同步
    /// </summary>
    public class DataSyncManager
    {
        private readonly IStatusRepository _localRepository;
        private readonly StatusSyncHelper _syncHelper;
        private bool _isSyncing = false;
        private DateTime _lastSuccessfulSync = DateTime.MinValue;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="localRepository">本地状态仓库</param>
        /// <param name="syncHelper">状态同步辅助类</param>
        public DataSyncManager(IStatusRepository localRepository, StatusSyncHelper syncHelper)
        {
            _localRepository = localRepository;
            _syncHelper = syncHelper;
        }

        /// <summary>
        /// 执行完全同步
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>同步是否成功</returns>
        public async Task<bool> PerformFullSyncAsync(Guid userId)
        {
            if (_isSyncing)
            {
                return false; // 正在同步中，避免重复同步
            }

            try
            {
                _isSyncing = true;
                
                // 1. 测试服务器连接
                bool isConnected = await _syncHelper.TestServerConnectionAsync();
                
                if (!isConnected)
                {
                    // 服务器不可用，尝试同步待处理的更改
                    await _syncHelper.SyncPendingChangesAsync();
                    return false;
                }
                
                // 2. 从服务器获取最新状态
                var serverStatus = await _syncHelper.GetLatestStatusFromServerAsync(userId);
                
                if (serverStatus != null)
                {
                    // 3. 获取本地当前状态
                    var localStatus = await _localRepository.GetCurrentStatusByUserIdAsync(userId);
                    
                    // 4. 解决冲突并更新本地数据
                    if (localStatus != null)
                    {
                        // 比较最后更新时间
                        if (serverStatus.LastUpdated > localStatus.LastUpdated)
                        {
                            // 服务器状态更新，更新本地
                            await _localRepository.EndCurrentStatusAsync(userId, DateTime.Now);
                            await _localRepository.AddAsync(serverStatus);
                        }
                        else if (serverStatus.LastUpdated < localStatus.LastUpdated)
                        {
                            // 本地状态更新，更新服务器
                            await _syncHelper.SyncStatusToServerAsync(localStatus);
                        }
                        // 如果时间相同，无需操作
                    }
                    else
                    {
                        // 本地没有状态，使用服务器状态
                        await _localRepository.AddAsync(serverStatus);
                    }
                }
                else
                {
                    // 从服务器获取失败，尝试将本地状态同步到服务器
                    var localStatus = await _localRepository.GetCurrentStatusByUserIdAsync(userId);
                    if (localStatus != null)
                    {
                        await _syncHelper.SyncStatusToServerAsync(localStatus);
                    }
                }
                
                // 5. 同步待处理的更改
                await _syncHelper.SyncPendingChangesAsync();
                
                _lastSuccessfulSync = DateTime.Now;
                return true;
            }
            catch (Exception ex)
            {
                // 记录错误日志
                Console.WriteLine($"同步失败: {ex.Message}");
                return false;
            }
            finally
            {
                _isSyncing = false;
            }
        }

        /// <summary>
        /// 仅同步当前状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>同步是否成功</returns>
        public async Task<bool> SyncCurrentStatusAsync(Guid userId)
        {
            try
            {
                // 1. 测试服务器连接
                bool isConnected = await _syncHelper.TestServerConnectionAsync();
                
                if (!isConnected)
                {
                    return false;
                }
                
                // 2. 获取本地当前状态
                var localCurrentStatus = await _localRepository.GetCurrentStatusByUserIdAsync(userId);
                
                if (localCurrentStatus != null)
                {
                    // 3. 同步到服务器
                    bool syncSuccess = await _syncHelper.SyncStatusToServerAsync(localCurrentStatus);
                    
                    if (syncSuccess)
                    {
                        _lastSuccessfulSync = DateTime.Now;
                    }
                    
                    return syncSuccess;
                }
                
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"当前状态同步失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 批量同步历史状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>成功同步的状态数量</returns>
        public async Task<int> SyncHistoricalStatusesAsync(Guid userId)
        {
            try
            {
                // 1. 测试服务器连接
                bool isConnected = await _syncHelper.TestServerConnectionAsync();
                
                if (!isConnected)
                {
                    return 0;
                }
                
                // 2. 获取本地历史状态（例如最近一个月的状态）
                var thirtyDaysAgo = DateTime.Now.AddDays(-30);
                var historicalStatuses = await _localRepository.GetByUserIdAsync(userId);
                
                // 过滤出未同步的状态
                var unsyncedStatuses = historicalStatuses
                    .Where(s => s.EndTime.HasValue && s.EndTime.Value >= thirtyDaysAgo && 
                                (!s.HasBeenSynced || s.LastUpdated > _lastSuccessfulSync))
                    .ToList();
                
                int successfulSyncs = 0;
                
                // 3. 逐个同步到服务器
                foreach (var status in unsyncedStatuses)
                {
                    if (await _syncHelper.SyncStatusToServerAsync(status))
                    {
                        // 标记为已同步
                        status.HasBeenSynced = true;
                        await _localRepository.UpdateAsync(status);
                        successfulSyncs++;
                    }
                }
                
                if (successfulSyncs > 0)
                {
                    _lastSuccessfulSync = DateTime.Now;
                }
                
                return successfulSyncs;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"历史状态同步失败: {ex.Message}");
                return 0;
            }
        }

        /// <summary>
        /// 获取上次成功同步的时间
        /// </summary>
        public DateTime LastSuccessfulSync => _lastSuccessfulSync;

        /// <summary>
        /// 获取是否正在同步
        /// </summary>
        public bool IsSyncing => _isSyncing;
    }
}